<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import axios from "axios";
import {
  Menu as IconMenu,
  Picture,
  ShoppingCartFull,
  Document,
  Upload,
  User,
  Fold,
  Expand,
  Share,
  InfoFilled,
  ArrowDown,
  SwitchButton,
  Plus,
} from "@element-plus/icons-vue";
import Dashboard from "../components/Dashboard.vue";
import Gallery from "../components/Gallery.vue";
import AlbumView from "./AlbumView.vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const activeIndex = ref("1");
const percentage = ref(35);
const isCollapse = ref(false);
const isUploadModalVisible = ref(false);
const imageType = ref<string[]>([]);
const tags = [
  { label: "🏞️ 风景", value: "landscape" },
  { label: "👤 人物", value: "portrait" },
  { label: "🏗️ 建筑", value: "architecture" },
  { label: "🍔 美食", value: "food" },
  { label: "🚗 交通工具", value: "vehicle" },
  { label: "🎨 艺术", value: "art" },
];

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value;
};

const switchPage = (index: string) => {
  activeIndex.value = index;
};
const activePageName = computed(() => {
  const pages: { [key: string]: string } = {
    "1": "仪表盘",
    "2": "我的图库",
    "3": "我的相册",
    "5": "账号设置",
  };
  return pages[activeIndex.value];
});

// 模拟上传接口地址
const uploadUrl = "http://localhost:3000/upload";

// 上传状态
const isUploading = ref(false);

// 表单数据
const uploadFormData = reactive({
  file: null,
  tags: [],
});

// 上传组件的引用
const uploadRef = ref(null);

// 选中的标签
const selectedTags = ref<string[]>([]);

// 打开上传弹窗
const openUploadModal = () => {
  isUploadModalVisible.value = true;
};

// 关闭上传弹窗
const closeUploadModal = () => {
  isUploadModalVisible.value = false;
  uploadFormData.file = null;
  selectedTags.value = [];
  // 清空上传文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 文件选择变化时的处理
const handleFileChange = (file: File) => {
  uploadFormData.file = file;
};

// 上传前的校验
const beforeUpload = (file: File) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPGOrPNG) {
    ElMessage.error("只能上传JPG或PNG格式的图片");
    return false;
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB");
    return false;
  }
  return true;
};

// 提交上传
const submitUpload = async () => {
  if (!uploadFormData.file) {
    ElMessage.error("请选择要上传的图片");
    return;
  }
  if (selectedTags.value.length === 0) {
    ElMessage.error("请选择至少一个标签");
    return;
  }

  isUploading.value = true;

  const formData = new FormData();
  formData.append("file", uploadFormData.file.raw);
  formData.append("tags", JSON.stringify(selectedTags.value));
  try {
    for (let [key, value] of formData.entries()) {
      if (key === "file") {
        console.log("从 FormData 获取的文件名: ", value);
      }
    }
    const response = await axios.post(uploadUrl, formData);

    if (response.status === 200) {
      ElMessage.success("图片上传成功");
      closeUploadModal();
    } else {
      ElMessage.error("图片上传失败");
    }
  } catch (error) {
    ElMessage.error("图片上传失败");
    console.error("上传出错：", error);
  } finally {
    isUploading.value = false;
  }
};

const router = useRouter();

// 添加退出登录方法
const handleLogout = () => {
  // 清除用户信息
  localStorage.removeItem("user");
  // 跳转到登录页
  router.push("/login");
};
</script>

<template>
  <el-container class="main-container">
    <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar">
      <div class="logo-container">
        <h1 v-show="!isCollapse">图库精灵</h1>
        <h1 v-show="isCollapse">Photo</h1>
      </div>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        active-text-color="#409EFF"
        background-color="#001529"
        text-color="#fff"
      >
        <el-menu-item index="1" @click="switchPage('1')">
          <el-icon><icon-menu /></el-icon>
          <span>仪表盘</span>
        </el-menu-item>

        <el-menu-item index="2" @click="switchPage('2')">
          <el-icon><Picture /></el-icon>
          <span>我的图库</span>
        </el-menu-item>

        <el-menu-item index="3" @click="switchPage('3')">
          <el-icon><FolderOpened /></el-icon>
          <span>我的相册</span>
        </el-menu-item>

        <el-menu-item index="5" @click="switchPage('5')">
          <el-icon><User /></el-icon>
          <span>账号设置</span>
        </el-menu-item>
      </el-menu>

      <div class="capacity" v-show="!isCollapse">
        <div class="capacity-info">
          <el-icon><InfoFilled /></el-icon>
          <span>存储空间 (已用 {{ percentage }}%)</span>
        </div>
        <el-progress
          :percentage="percentage"
          :text-inside="true"
          stroke-width="18"
          color="#409EFF"
          track-color="#15345A"
        />
        <div class="storage-details">
          <span>15.8 GB / 100 GB</span>
        </div>
      </div>
    </el-aside>

    <el-container>
      <el-header class="main-header">
        <div class="header-content">
          <div class="header-left">
            <el-button type="text" class="toggle-button" @click="toggleSidebar">
              <el-icon class="collapse-icon">
                <Fold v-if="!isCollapse" />
                <Expand v-else />
              </el-icon>
            </el-button>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>控制台</el-breadcrumb-item>
              <el-breadcrumb-item>{{ activePageName }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <el-button
              type="primary"
              class="upload-btn"
              @click="openUploadModal"
            >
              <el-icon><Upload /></el-icon>上传
            </el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <el-avatar :size="32" :icon="User" class="user-avatar" />
                <span class="username">arihu</span>
                <el-icon class="arrow-down"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item class="dropdown-item">
                    <el-icon><User /></el-icon>个人中心
                  </el-dropdown-item>
                  <el-dropdown-item
                    divided
                    class="dropdown-item"
                    @click="handleLogout"
                  >
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-main class="main-content">
        <Dashboard v-if="activeIndex === '1'" />
        <Gallery v-if="activeIndex === '2'" />
        <AlbumView v-if="activeIndex === '3'" />
        <!-- 其他页面组件 -->
      </el-main>
    </el-container>

    <el-dialog
      v-model="isUploadModalVisible"
      title="上传图片"
      width="50%"
      :close-on-click-modal="false"
      class="upload-dialog"
      @close="closeUploadModal"
    >
      <el-form ref="uploadForm" :model="uploadFormData">
        <!-- 文件上传 -->
        <el-form-item label="选择图片">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            list-type="picture-card"
          >
            <template #trigger>
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload>
        </el-form-item>
        z
        <!-- 图片标签选择 -->
        <el-form-item label="图片标签">
          <el-checkbox-group v-model="selectedTags" :max="3">
            <el-checkbox
              v-for="tag in tags"
              :key="tag.value"
              :label="tag.value"
            >
              {{ tag.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="tag-tip">最多选择3个标签</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeUploadModal">取消</el-button>
          <el-button
            type="primary"
            @click="submitUpload"
            :loading="isUploading"
          >
            上传图片
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<style scoped>
.main-container {
  height: 100vh;
  background: #f0f2f5;
}

.sidebar {
  background: #001529;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #002140;
  h1 {
    color: #fff;
    font-size: 20px;
    margin: 0;
    transition: opacity 0.3s;
  }
}

.el-menu {
  border-right: none;
  flex: 1;
  .el-menu-item {
    transition: all 0.3s;
    height: 48px;
    line-height: 48px;
    margin: 4px 0;

    &:hover {
      background-color: rgba(255, 255, 255, 0.1) !important;
    }

    &.is-active {
      background-color: #1890ff !important;
      border-radius: 4px;
      margin: 4px 8px;
    }

    .el-icon {
      font-size: 18px;
      margin-right: 8px;
    }
  }
}

.capacity {
  padding: 20px;
  background: #001529;
  .capacity-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #8c9bb2;
    margin-bottom: 12px;
    font-size: 13px;

    .el-icon {
      font-size: 16px;
    }
  }

  .storage-details {
    color: #637a9d;
    font-size: 12px;
    margin-top: 8px;
    text-align: center;
  }
}

.main-header {
  height: 60px;
  padding: 0 24px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

  .header-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;

  .toggle-button {
    padding: 8px;
    font-size: 20px;
    color: #666;

    &:hover {
      color: #409eff;
    }
  }

  .el-breadcrumb {
    font-size: 16px;

    :deep(.el-breadcrumb__inner) {
      font-weight: 500;
    }
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;

  .upload-btn {
    padding: 8px 16px;
    border-radius: 4px;
    transition: all 0.3s;

    .el-icon {
      margin-right: 6px;
    }
  }

  .el-dropdown-link {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 4px 12px;
    border-radius: 20px;
    transition: background-color 0.3s;

    &:hover {
      background-color: #f5f7fa;
    }

    .user-avatar {
      background: #409eff;
    }

    .username {
      font-weight: 500;
      color: #333;
      font-size: 14px;
    }

    .arrow-down {
      color: #666;
      font-size: 12px;
    }
  }
}

.main-content {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.collapse-icon {
  transition: transform 0.3s;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  font-size: 14px;

  .el-icon {
    font-size: 16px;
  }
}

.el-menu--collapse {
  .el-menu-item {
    padding: 0 19px !important;

    .el-icon {
      margin-right: 0;
    }
  }
}

/*上传弹窗*/
.upload-dialog {
  .el-dialog__header {
    background-color: #f5f7fa;
    padding: 16px 24px;
  }
  .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
  }
  .el-form-item {
    margin-bottom: 16px;
  }
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
    font-size: 24px;
  }
  .tag-tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px;
    background-color: #f5f7fa;
    border-top: 1px solid #e4e7ed;
  }
}
</style>
